﻿package game.libs {
	import game.objects.GameObject;
	import game.objects.LibObject;
	import game.swfloader.*;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.display.MovieClip;
	import flash.events.ProgressEvent;
	
	public class Libs extends GameObject {
		
		private var arr:Vector.<LibObject> = new Vector.<LibObject>;
		private var current_load:int = 0;
		
		public var progress:Number = 0;
		
		public function Libs():void {
			
		}
		
		public function add (lib:LibObject):void {
			arr.push(lib);
		}
		
		public function load():void {
			loadLib();
		}
		
		private function loadLib():void {
			if (arr.length>0 && current_load<arr.length) {
				var lib:LibObject = arr[current_load];
				var swfloader:SWFLoader = new SWFLoader;
				swfloader.addEventListener( SWFLoaderEvent.LOADED,	loadedHandler );
				swfloader.addEventListener( SWFLoaderEvent.ERROR,	errorHandler );
				swfloader.addEventListener( ProgressEvent.PROGRESS, progressHandler );
				swfloader.load( new URLRequest ( config.host + config.dirs.libs + lib.url ), new LoaderContext ( false ) );
			} else {
				loaded();
			}
		}
		
		private function loadedHandler(event:SWFLoaderEvent):void {
			arr[current_load].data = event.content;
			
			current_load ++;
			
			loadLib();
		}
		
		public function get (title:String):MovieClip {
			var mc:MovieClip;
			for each (var lib:LibObject in arr) {
				if (lib.title==title) {
					mc = lib.data;
					break;
				}
			}
			return mc;
		}
		
		private function errorHandler(event:SWFLoaderEvent):void {
			this.dispatchEvent( new LibsEvent ( LibsEvent.ERROR ) ); 
		}
		
		private function loaded() {
			this.dispatchEvent( new LibsEvent ( LibsEvent.COMPLETE ) ); 
		}
		
		private function progressHandler(event:ProgressEvent) {
			var p:Number = (event.target as SWFLoader).progress;
			var one:Number = current_load/arr.length;
			
			progress = one + p/arr.length;
			
			this.dispatchEvent( new ProgressEvent ( ProgressEvent.PROGRESS ) );
		}
	}
}